package com.interesting.client.UI.commonActivity;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.interesting.base.http.HttpUtil;
import com.interesting.base.utils.SQLiteUtil;
import com.interesting.client.application.AppHolder;
import com.interesting.client.application.TradeApplication;
import com.interesting.client.widget.dialog.AlertDialogFragment;
import com.interesting.client.widget.dialog.MessageDialogFragment;

public class UIUtil {
	public static void showTimeOutToast(Context context) {
		Toast toast = Toast.makeText(context, "网络超时", Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	/** 显示Toast */
	public static void showToast(Context context, CharSequence text) {
		Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	/** 显示LongToast */
	public static void showLongToast(Context context, CharSequence text) {
		Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	/**
	 * 收藏的异步操作 userId 用户 infoId收藏的ID
	 * */
	public static class FavouriteTask extends AsyncTask<String, Void, JSONObject> {
		private Context context;
		private String type;

		public FavouriteTask(Context context) {
			this.context = context;
		}

		@Override
		protected JSONObject doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("act", "favourites");
			map.put("userId", params[0]);
			map.put("infoId", params[1]);
			map.put("type", params[2]);
			type = params[2];
			JSONObject result = HttpUtil.parseResult(HttpUtil.post(map));
			return result;
		}

		@Override
		protected void onPostExecute(JSONObject result) {

			if (result != null) {
				if (type.equals("0"))
					showToast(context, "收藏成功");
				else {
					showToast(context, "取消收藏成功");

				}
			}
		}
	}

	/** 显示一个信息dialog fm =getSupportFragmentManager() */
	public static void showMessageDialog(FragmentManager fm, String message) {
		FragmentTransaction ft = fm.beginTransaction();
		Fragment prev = fm.findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		MessageDialogFragment dialog = MessageDialogFragment.newInstance(message);
		dialog.show(fm, "dialog");

	}

	/** 显示一个等待dialog */
	public static void showWaitDialog(FragmentManager fm) {
		FragmentTransaction ft = fm.beginTransaction();
		Fragment prev = fm.findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		MessageDialogFragment dialog = MessageDialogFragment.newInstance("请稍等...");
		dialog.show(fm, "dialog");

	}

	/** AlertDialog */
	public static void showAlertDialog(FragmentManager fm, String title, String message, String positiveButtonText,
			String negativeButtonText, OnClickListener positiveListener, OnClickListener negativeListener) {
		FragmentTransaction ft = fm.beginTransaction();
		Fragment prev = fm.findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		AlertDialogFragment dialog = AlertDialogFragment.newInstance(title, message, positiveButtonText,
				negativeButtonText);
		dialog.setNegativeListener(negativeListener);
		dialog.setPositiveListener(positiveListener);
		dialog.show(fm, "dialog");

	}

	/** 隐藏一个等待dialog fm=getSupportFragmentManager() */
	public static void hideDialog(FragmentManager fm) {
		DialogFragment prev = (DialogFragment) fm.findFragmentByTag("dialog");
		if (prev != null) {
			prev.dismiss();
		}
	}

	/** 打电话拨号 */
	public static void dial(Context context, String telephone) {
		Uri uri = Uri.parse("tel:" + telephone);
		Intent intent = new Intent(Intent.ACTION_DIAL, uri);
		context.startActivity(intent);
	}

	/** 打开网页 */
	public static void openWeb(Context context, String url) {
		try {
			Uri uri = Uri.parse(url);
			context.startActivity(new Intent(Intent.ACTION_VIEW, uri));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/** 判断是否已登录 */
	public static boolean isLoggedIn() {
		if (AppHolder.getInsatnce().user.getUserId() == null || AppHolder.getInsatnce().user.getUserId().equals("")) {
			return false;
		} else {
			return true;
		}
	}

	/** 赞或踩 */
	public static class TopOrDownAsync extends AsyncTask<String, Void, JSONObject> {
		private SQLiteUtil sqllite;
		private Context context;
		public final String[] allColumns = { SQLiteUtil.HOME_ID, SQLiteUtil.HOME_JOKEID, SQLiteUtil.HOME_JOKESTATE };

		public TopOrDownAsync(Context context) {
			this.context = context;
		}

		@Override
		protected JSONObject doInBackground(String... params) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("Id", params[0]);
			map.put("type", params[1]);
			//数据库查询
			sqllite=AppHolder.getInsatnce().dbAdapter;
			Cursor cursor = sqllite.getWritableDatabase().query(SQLiteUtil.TABLE_JOKE, allColumns, "jokeid=?",
					new String[] { params[0] }, null, null, null);

			ContentValues values = new ContentValues();
			if (cursor.getCount()==0) {
				map.put("act", "topORdown");
				values.put(SQLiteUtil.HOME_JOKEID, params[0]);
				values.put(SQLiteUtil.HOME_JOKESTATE, params[1]);
				sqllite.getWritableDatabase().insert(SQLiteUtil.TABLE_JOKE, null, values);
			} else {
				map.put("act", "changeTopORdown");
				values.put(SQLiteUtil.HOME_JOKESTATE, params[1]);
				sqllite.getWritableDatabase().update(SQLiteUtil.TABLE_JOKE, values, "jokeid=?", new String[] { params[0] });
			}
			cursor.close();
			return HttpUtil.parseResult(HttpUtil.post(map));
		}

		@Override
		protected void onPostExecute(JSONObject result) {
			
			Log.d("TAG", "成了");
			
		}

	}

	public static boolean isIntentSafe(Activity activity, Uri uri) {
		Intent mapCall = new Intent(Intent.ACTION_VIEW, uri);
		PackageManager packageManager = activity.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(mapCall, 0);
		return activities.size() > 0;
	}

	public static boolean isIntentSafe(Activity activity, Intent intent) {
		PackageManager packageManager = activity.getPackageManager();
		List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
		return activities.size() > 0;
	}

	public static int getScreenWidth() {
		Activity activity = TradeApplication.getInstance().getActivity();
		if (activity != null) {
			Display display = activity.getWindowManager().getDefaultDisplay();
			DisplayMetrics metrics = new DisplayMetrics();
			display.getMetrics(metrics);
			return metrics.widthPixels;
		}

		return 480;
	}

	public static int getScreenHeight() {
		Activity activity = TradeApplication.getInstance().getActivity();
		if (activity != null) {
			Display display = activity.getWindowManager().getDefaultDisplay();
			DisplayMetrics metrics = new DisplayMetrics();
			display.getMetrics(metrics);
			return metrics.heightPixels;
		}
		return 800;
	}

	public static void closeSilently(Closeable closeable) {
		if (closeable != null)
			try {
				closeable.close();
			} catch (IOException ignored) {

			}
	}

	public static void cancelTasks(AsyncTask... tasks) {
		for (AsyncTask task : tasks) {
			if (task != null)
				task.cancel(true);
		}
	}

	// 设置listView 高度
	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}
}
